package com.vogue.supplymall.account.controller;

import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.vogue.supplymall.account.domain.bean.ConstantBean;
import com.vogue.supplymall.account.domain.bean.PropertiesConfig;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.common.exception.DataInconsistentException;
import com.vogue.supplymall.common.exception.TimeOutException;

/**
 * Created by Administrator on 2017-11-28.
 */
@RequestMapping("/suppliermall")
public class BaseController extends com.vogue.ssm.controller.BaseController {

    @Autowired
    protected PropertiesConfig propertiesConfig;

    @Autowired
    protected MessageSourceUtils messageSourceUtils;

    /**
    * 验证短息激活码是否有效<br>
    * @param request 请求对象
    * @param code 验证码
    */
    @SuppressWarnings({ "unchecked"})
    public void verifymsmcode(HttpServletRequest request, String code) {
        Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute(ConstantBean.REQ_ACTIVATION_CODE);
        if (map != null) {
            Date date = (Date) map.get(ConstantBean.REQ_VERIFYMSMCODE_TIME);
            Date now = new Date();
            long time = now.getTime() - date.getTime();
            if (propertiesConfig.getActcodeEffectiveTime() < time) {
                // 超过15分钟有效期
                throw new TimeOutException(messageSourceUtils.getMessage(com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
                        + ConstantBean.REQ_CHECKCODE_KEY, null));
            } else {
                if (code == null || !code.equals((String) map.get(ConstantBean.REQ_VERIFYMSMCODE_CODE))) {
                    // 手机验证码不一致
                    throw new DataInconsistentException(messageSourceUtils.getMessage(com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
                            + ConstantBean.REQ_CHECKCODE_KEY, null));
                } else {
                    request.getSession().removeAttribute(ConstantBean.REQ_ACTIVATION_CODE);
                    request.removeAttribute(ConstantBean.REQ_CHECKCODE_KEY);
                }
            }
        } else {
            if (StringUtils.isNotEmpty(code)) {
                throw new DataInconsistentException(
                        messageSourceUtils.getMessage(com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
                                + ConstantBean.REQ_CHECKCODE_KEY, null));
            }
        }
    }
}
